package com.helei.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.helei.data.entity.SysMenu;
import com.helei.data.entity.SysRole;
import com.helei.data.entity.SysUser;
import com.helei.data.service.SysMenuService;
import com.helei.data.service.SysRoleService;
import com.helei.data.service.SysUserService;
import com.helei.security.component.UserAuthentication;
import com.helei.security.entity.SecurityUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    SysUserService userService;
    @Autowired
    SysRoleService roleService;
    @Autowired
    SysMenuService menuService;

    //根据 账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //将来连接数据库根据账号查询用户信息
        //暂时采用模拟数据
        // UserDetails build = User.withUsername("admin").password("123").authorities("a").build();

        //数据库查询用户
        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAccount, username));
        //查询角色
        List<SysRole> roles = roleService.selectUserRole(sysUser.getId());
     /*   String role = "update,a";
        String[] roles = role.split(",");*/
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SysRole s : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + s.getCode()));
        }
        //查询菜单
        List<SysMenu> menuList = menuService.selectUserRoleMenu(roles.stream().map(SysRole::getId).collect(Collectors.toList()));
        UserAuthentication myUser = new UserAuthentication(username, sysUser.getPassword(), authorities);
        myUser.setExtendUserBean(SecurityUserEntity.builder().id(sysUser.getId()).name(sysUser.getAccount()).password(sysUser.getPassword()).build());

        myUser.setRoles(roles.stream().map(SysRole::getCode).collect(Collectors.toList()));
        myUser.setMenu(menuList);
        // UserDetails build = User.withUsername(username).password(securityUserEntity.getPassword()).roles("a").build();
        //return new User(username, securityUserEntity.getPassword(), authorities);
        return myUser;
    }

}
